﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UIShell.OSGi;

namespace Pasys.PresentationCore.WinForms
{
    class ToolbarStatusMonitor
    {
        public ToolbarStatusMonitor(string toolbarName, Action<bool> changeVisible)
        {
            if (string.IsNullOrEmpty(toolbarName))
            {
                throw new ArgumentException();
            }
            ChangeVisible = changeVisible;

            var commandService = BundleRuntime.Instance.GetFirstOrDefaultService<ICommandBusService>();
            if (commandService != null)
            {
                commandService.SubscribeToolbarStatusEvent(toolbarName,
                                                           (sender, e) => UIInvoke(() => OnCommandReceived(sender, e)));
            }
        }

        public ToolbarStatusMonitor(string toolbarName)
            : this(toolbarName, null)
        {
        }

        public Action<bool> ChangeVisible { get; set; }

        private void UIInvoke(Action action)
        {
            var layoutView = BundleRuntime.Instance.GetFirstOrDefaultService<IShellLayoutViewProxy>();
            layoutView.Invoke(action);
        }

        private void OnCommandReceived(object sender, object e)
        {
            var contact = (ControlStatusContact)e;

            switch (contact.Status)
            {
                case CommandStatus.Hide:
                    if (ChangeVisible != null)
                    {
                        ChangeVisible(false);
                    }
                    break;
                case CommandStatus.Visible:
                    if (ChangeVisible != null)
                    {
                        ChangeVisible(true);
                    }
                    break;

                default:
                    break;
            }
        }

    }
}
